package com.rfid.afd.activity.demo;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AnimationUtils;
import android.view.animation.LayoutAnimationController;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.rfid.db.bean.Machine;
import com.rfid.rls_psw.R;
import com.rfid.util.RfidManager;
import com.rfid.util.AnimatorHelper;
import com.rfid.util.DBManager;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;

public class BorrowActivity extends AppCompatActivity implements RfidManager.RfidListener {

    @BindView(R.id.readerId)
    TextView mTextView;
    @BindView(R.id.recyclerview)
    RecyclerView mRecyclerView;

    @BindView(R.id.edit)
    EditText mEditText;

    private List<Machine> mNotes;
    protected Map<String,Integer> mBarIndex;
    protected List<Machine> mData;
    private BorrowActivity.MyAdapter myAdapter;
    private String mId;

    @BindView(R.id.rssi)
    EditText mRssi;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_borrow);
        ButterKnife.bind(this);

        mNotes = DBManager.queryMachines();
        mBarIndex = new HashMap<>();
        for(int i=0;i<mNotes.size();i++) {
            mBarIndex.put(mNotes.get(i).getEpc(),i);
        }
        mData = new ArrayList<>();
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        mRecyclerView.addItemDecoration(new DividerItemDecoration(this,RecyclerView.VERTICAL));
        myAdapter = new BorrowActivity.MyAdapter(mData);
        mRecyclerView.setAdapter(myAdapter);
        LayoutAnimationController controller = new LayoutAnimationController(AnimationUtils.loadAnimation(this,android.R.anim.fade_in));
        mRecyclerView.setLayoutAnimation(controller);

        mEditText.setError("请输入读者证号");
        RfidManager.getInstance().setRfidListener(this);
        RfidManager.getInstance().setOutputPower(15);
        mRssi.setText("" + 15);
    }


    public static void startActivity(Context context) {
        Intent intent = new Intent();
        intent.setClass(context,BorrowActivity.class);
        context.startActivity(intent);
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        RfidManager.getInstance().stop();
        RfidManager.getInstance().setRfidListener(null);
    }

    @Override
    public void onRfid(String rfid) {
        if(mBarIndex.containsKey(rfid)) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Machine machine = mNotes.get(mBarIndex.get(rfid));
                    if (!mData.contains(machine)) {
                        mData.add(machine);
                        myAdapter.notifyDataSetChanged();
                    }
                }
            });
        }
    }

    @Override
    public void onOutputPower(int power) {
        mRssi.setText(power + "");
    }

    public void rssiConfirm(View view) {
        String rssi = mRssi.getText().toString();
        if(TextUtils.isEmpty(rssi)) {
            return;
        }
        RfidManager.getInstance().setOutputPower(Integer.valueOf(rssi));

        RfidManager.getInstance().getOutputPower();
    }

    public void back(View view) {
        onBackPressed();
    }

    public void readerConfirm(View view) {
        String text = mEditText.getText().toString();
        if(TextUtils.isEmpty(text)) {
            mEditText.setError("请输入读者证号");
            AnimatorHelper.shake(this,mEditText);
            return;
        }
        mId = text;
        mTextView.setText("请扫描需要借用的设备标签,当前读者证:" + text);
        RfidManager.getInstance().start();
    }

    public void confirm(View view) {
        String text = mEditText.getText().toString();
        if(TextUtils.isEmpty(text)) {
            mEditText.setError("请输入读者证号");
            AnimatorHelper.shake(this,mEditText);
            return;
        }
        int count = 0;
        for(Machine machine : mData) {
            if(!TextUtils.isEmpty(machine.getIdCard()))
                continue;
            machine.setIdCard(mId);
            DBManager.updateMachine(machine);
            count ++;
        }
        if(count == 0) {
            Toast.makeText(this,"请扫描要借用的设备",Toast.LENGTH_SHORT).show();
            return;
        }
        Toast.makeText(this,"共借出" + count + "件",Toast.LENGTH_SHORT).show();
        myAdapter.notifyDataSetChanged();
    }

    public class MyAdapter extends RecyclerView.Adapter<BorrowActivity.MyAdapter.MyViewHolder> {

        private List<Machine> mRfids;

        public MyAdapter(List<Machine> data) {
            mRfids = data;
        }

        @NonNull
        @Override
        public BorrowActivity.MyAdapter.MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            return new BorrowActivity.MyAdapter.MyViewHolder(getLayoutInflater().inflate(R.layout.check_machine_item,parent,false));
        }

        @Override
        public void onBindViewHolder(@NonNull BorrowActivity.MyAdapter.MyViewHolder holder, int position) {
            Machine machine = mRfids.get(position);
            holder.name.setText(machine.getInfo());
            holder.barcode.setText(machine.getEpc());
            String reader = machine.getIdCard();
            if(TextUtils.isEmpty(reader)) {
                holder.idcard.setText("");
                holder.itemView.setBackgroundColor(Color.WHITE);
            } else {
                holder.idcard.setText("已出借");
                holder.itemView.setBackgroundColor(Color.YELLOW);
            }
        }

        @Override
        public int getItemCount() {
            return mRfids.size();
        }

        class MyViewHolder extends RecyclerView.ViewHolder {
            @BindView(R.id.book_name)
            TextView name;
            @BindView(R.id.barcode)
            TextView barcode;
            @BindView(R.id.idcard)
            TextView idcard;
            public MyViewHolder(@NonNull View itemView) {
                super(itemView);
                ButterKnife.bind(this,itemView);
            }
        }
    }
}